package com.example.demo.filter;

import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/*
 * token校验
 */
public class JwtAuthenzacationFilter extends BasicAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JwtAuthenzacationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
       String token = request.getParameter("token");
       if (token == null || !token.startsWith("Bearer")){
           chain.doFilter(request,response);
           return;
       }
        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
       SecurityContextHolder.getContext().setAuthentication(authenticationToken);
       chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token=request.getParameter("token");
        if (token!=null){
            String user = Jwts.parser().setSigningKey("JwtSerct")
                    .parseClaimsJws(token.replace("Bearer",""))
                    .getBody().getSubject();
            if (user!=null){
                return new UsernamePasswordAuthenticationToken(user,null,Collections.emptyList());
            }
            return null;
        }
        return null;
    }

}
